package com.bruce.cloud.feign.service;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpFilter;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.Serial;
import java.util.Enumeration;

/**
 * Created by bruce in 2025/6/18 21:42
 */
@Component
public class RequestLogFilter extends HttpFilter {
    private static final Logger log = LoggerFactory.getLogger(RequestLogFilter.class);

    @Serial
    private static final long serialVersionUID = -8372457981640874402L;


    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        // 打印请求基本信息
        System.out.println("=== Request Info ===");
        log.info("Method: {}, URL: {}", req.getMethod(), req.getRequestURL());
        log.info("queryString: {}", req.getQueryString());

        // 打印请求头
        System.out.println("--- Headers ---");
        Enumeration<String> headerNames = req.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            log.info("header: {}, value: {}", headerName, req.getHeader(headerName));
        }
        super.doFilter(request, response, chain);

    }
}
